

function Promise(executor){

    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null
    //声明一个属性
    this.callbacks=[];
    //保存实例对手的 this 的值
    const self = this ;

    //resolve 函数
    function resolve(data){
        //判断状态
        if(self.PromiseState !=='pending') return;

        //修改对象状态 （promiseState）
        self.PromiseState = 'fulfilled'
        //设置对象结果值(promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item=>{
            item.onResolved(data)
        })
    }
    //reject 函数
    function reject(data){
        //判断状态
        if(self.PromiseState !=='pending') return;
        //修改对象状态 （promiseState）
        self.PromiseState = 'rejected'
        //设置对象结果值(promiseResult)
        self.PromiseResult = data;
        self.callbacks.forEach(item=>{
            item.onRejected(data)
        })
    }

    try{
        //执行器函数是同步调用的
        executor(resolve,reject);
    }catch(e){
        //修改promise对象状态为失败
        reject(e)
    }
    


}
//添加 then 方法
Promise.prototype.then=function(onResolved,onRejected){
    const self = this;
    return new Promise((resolve,reject)=>{
        function callback(type){
            try{
                //执行成功的回调函数
                let result = type(self.PromiseResult);
                //判断
                if(result instanceof Promise){
                    result.then(v=>{
                        resolve(v)
                    },r=>{
                        reject(r)
                    })
                }else{
                    resolve(result)
                }
           }catch(e){
               reject(e)
           }
        }
        //调用回调函数 promiseState
    if(this.PromiseState === 'fulfilled'){
       callback(onResolved)
    }

    if(this.PromiseState === 'rejected'){
        callback(onRejected)
    }
    //判断pending 状态
    if(this.PromiseState ==='pending'){
        //保存回调函数
        this.callbacks.push({
           onResolved:function(){
            callback(onResolved)
               
            },
            onRejected:function(){
                
                callback(onRejected)
            }
        })
    }
    })
    
}